import { View, Text, Image, Video } from "@tarojs/components";
import Taro, { useUnload } from "@tarojs/taro";
import React, { useEffect, useState } from 'react'
import { uploadVideo, watchVideo } from "../../../../api/video.js";
import { iconAdd, iconDown, iconPlay } from "../../../../assets/files.js";
import useNavInfo from "../../../../hooks/useNavInfo.js";
import "./index.scss";

export default function VideoList(props) {
  const { videoList, changeIsPoster } = props;
  const [videoId, setVideoId] = useState("");
  const [last, setLast] = useState("");

  useUnload(() => {
    videoId && watchVideo({ videoId, videoType: 'end', frequency: 3 })
  })

  function copyTextToClipboard(text) {
    Taro.setClipboardData({
      data: text,
      success: function () {
        console.log('Text copied to clipboard');
        // 可以添加用户友好的提示，例如使用Taro.showToast
        Taro.showToast({
          title: '复制成功',
          icon: 'success',
          duration: 2000
        })
      },
      fail: function () {
        console.error('Could not copy text');
        // 可以添加错误处理或用户友好的提示
      }
    });
  }



  function downVideo(src, id) {

    Taro.showLoading({ title: '下载中...' })
    Taro.downloadFile({
      url: src, //仅为示例，并非真实的资源
      success(res) {
        if (res.statusCode === 200) {
          Taro.saveVideoToPhotosAlbum({
            filePath: res.tempFilePath,
            success: function (res) {
              Taro.hideLoading();
              Taro.showToast({ title: '下载成功，视频已保存到相册' })
              setVideoCount(id)
            },
            fail(err) {
              console.log("err", err);
              Taro.hideLoading();
              Taro.showModal({
                title: "获取保存到相册权限失败，点击确定打开",
                complete(res) {
                  console.log(res);
                  if (res.confirm) {
                    Taro.openSetting({
                      success(settingdata) {
                        console.log(settingdata)
                        if (settingdata.authSetting["scope.writePhotosAlbum"]) {
                          Taro.showToast({
                            title: "获取权限成功，再次点击图片保存到相册",
                            icon: 'none'
                          })
                        } else {
                          console.log("获取权限失败")
                        }
                      }
                    })

                  }
                }
              })

            }
          })
        }
      },
      fail(err) {
        Taro.hideLoading();
        console.log(err);
        if (err.errMsg == 'downloadFile:fail exceed max file size') {
          Taro.showModal({
            title: '视频大于200M，点击复制链接到浏览器下载',
            confirmText: "复制",
            complete: ((res) => {
              if (res.confirm) {
                copyTextToClipboard(src);
              }
            })
          })
        } else {
          Taro.showModal({
            title: '下载异常，点击复制链接到浏览器下载',
            confirmText: "复制",
            complete: ((res) => {
              if (res.confirm) {
                copyTextToClipboard(src);
              }
            })
          })
        }



      }
    })
  }

  function setVideoCount(videoId) {
    uploadVideo({ videoId })
  }

  function start(e, item, index) {
    setLast(index)
    watchVideoFn(item.id, 'start', videoId === item.id ? 2 : 1)
    if (last !== index && videoId) {
      watchVideoFn(videoId, 'end', 3)
    }
  }

  function pause(e, item, index) {
    console.log(e);
    watchVideoFn(item.id, 'end', 3)
  }

  function end(e, item, index) {
    if (Taro.getSystemInfoSync().platform === 'android') {
      watchVideoFn(videoId, 'end', 3)
    }

  }

  function watchVideoFn(videoId, videoType, frequency) {
    watchVideo({ videoId, videoType, frequency }).then(res => {
      if (res.success) {
        if (videoType === 'end') {
          setVideoId()
        } else {
          setVideoId(videoId)
        }

      }
    })
  }

  function playVideo(item, index) {

    changeIsPoster(item, index)
  }

  function timeUpdate(e) {
    // console.log(e);
  }

  const [direction, setDirection] = useState(90);

  return (
    <View className="warp">
      {
        videoList?.map((v, i) => {
          return (
            <View className="videoItem" key={i}>
              {
                v.isPoster === 1 ?
                  <View className="posterWrap" onClick={() => playVideo(v, i)}>
                    <Image className="poster" mode="aspectFill" src={v.imageFileUrl} />
                    <Image className="playBtn" src={iconPlay} />
                  </View>
                  :
                  <>
                    <Video
                      id={`video-${i}`}
                      className="video"
                      poster={iconAdd}
                      src={v.src}
                      customCache={false}
                      autoplay={true}
                      direction={direction}
                      initialTime={0}
                      controls
                      enablePlayGesture
                      loop={false}
                      muted={false}
                      showFullscreenBtn={true}
                      // playBtnPosition="center"
                      onPlay={(e) => start(e, v, i)}
                      onPause={(e) => pause(e, v, i)}
                      onEnded={(e) => end(e, v, i)}
                      onLoadedMetaData={(e) => {
                        const { width, height } = e.detail
                        if (width > height) {
                          setDirection(90)
                        } else {
                          setDirection(0)
                        }
                      }}
                    />

                  </>

              }

              <View className="videoTitle">
                <Text className="vTit">{v.videoName}</Text>
                {/* <Image onClick={async () => downVideo(v.src, v.id)} className="iconDown" src={iconDown} /> */}
              </View>

              {/* <View className="itemBottom">
                <Text className="cTime">{v.publishDate.substring(0, 11)}</Text>
                <Image onClick={async () => downVideo(v.src, v.id)} className="iconDown" src={iconDown} />
              </View> */}

            </View>
          )
        })
      }

    </View>
  );
}
